package com.tuanzi.loan.business.service.system.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tuanzi.loan.business.entity.system.Announcement;
import com.tuanzi.loan.business.repository.system.AnnouncementRepository;
import com.tuanzi.loan.business.service.system.AnnouncementService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.repository.JPAAuditRepository;
import com.tuanzi.loan.core.service.BaseAuditServiceImpl;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.system.AnnouncementSearchRequest;
import com.tuanzi.loan.vo.response.system.AnnouncementSearchResponse;

/**
 * @author Ray 2017/09/21
 */
@Debug
@Service
@Transactional
@Retryable(value = { RetryException.class })
public class AnnouncementServiceImpl extends BaseAuditServiceImpl<Announcement, String> implements AnnouncementService {

	@Autowired
	private AnnouncementRepository announcementRepository;

	@Override
	protected JPAAuditRepository<Announcement, String> getRepository() {
		return announcementRepository;
	}

	@Override
	public Page<AnnouncementSearchResponse> list(PageSearcher<AnnouncementSearchRequest> pageSearcher) {
		return announcementRepository.list(pageSearcher.getSearchCondition(), pageSearcher.getPageable());
	}

	@Override
	public List<Announcement> findCurrentAnnouncement() {
		Date now = new Date();
		return announcementRepository.findAllByStartTimeBeforeAndEndTimeAfter(now, now);
	}

	@Override
	public List<Announcement> findAllNeedToSendAnnouncements() {
		Date now = new Date();
		return announcementRepository.findAllByStartTimeBeforeAndEndTimeAfterAndSendEmailAndHasSendEmail(now, now, Boolean.TRUE, Boolean.FALSE);
	}

	@Override
	public Announcement saveOrUpdate(Announcement announcement) {
		if (StringUtils.isBlank(announcement.getId())) {
			announcement.setHasSendEmail(false);
		}
		return super.saveOrUpdate(announcement);
	}
}
